package org.xxpay.pay.channel.tiancheng;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@Service
public class TianchengPaymentService extends BasePayment {

    private final static String logPrefix = "【天诚支付】";
    @Override
    public String getChannelName() {
        return TianchengConfig.CHANNEL_NAME;
    }

    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder){
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder){
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有订单查询接口");
        return retObj;
    }

    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder){
        TianchengConfig config = new TianchengConfig(getPayParam(payOrder));
        Map<String,Object> params = Maps.newHashMap();
        //设置请求参数
        setParams(payOrder, config, params);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));
        //将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
//        String reslut=null;
//        try {
//            reslut = HtmlUtils.sendHttpPost(config.getRequestUrl()+TianchengConfig.REQ_PAY_URL_FIXX,JSON.toJSONString(params));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        JSONObject origin = JSONObject.parseObject(reslut);
//        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
//        // 响应对象
//        JSONObject retObj = new JSONObject();
//        if(StringUtils.equals("00",origin.getString("code"))){
//            return  buildPayResultOfForm(retObj, payOrder,"<script type=\"text/javascript\">\n" +
//                        "　　window.location.href=\""+ origin.getString("Data")+"\";\n" +
//                        "　　</script>" );
//
//        }
//        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
//        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.toJSONString());
//        return retObj;
        JSONObject retObj = new JSONObject();
        String payForm = HtmlUtils.form(config.getRequestUrl()+TianchengConfig.REQ_PAY_URL_FIXX, HtmlUtils.POST, params);

        return buildPayResultOfForm(retObj, payOrder, payForm);
    } 

    //设置请求参数
    private void setParams(PayOrder payOrder, TianchengConfig config,Map<String,Object> params){

        params.put("merchant", config.getAppId());
        params.put("qrtype", config.getPayMode());
        params.put("customno", payOrder.getPayOrderId());
        params.put("money", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        params.put("sendtime", timestampToDate());
        params.put("notifyurl", payConfig.getNotifyUrl(getChannelName()));
        params.put("backurl","");
        params.put("risklevel","");
        params.put("sign", getSign(params, config.getPrivateKey()));
    }
    //获取sign
    private String getSign(Map<String,Object> params,String key){
        String signTxt = "merchant="+params.get("merchant").toString()+////SignUtils.parameterText(params);
                         "&qrtype="+params.get("qrtype").toString()+
                         "&customno="+params.get("customno").toString()+
                         "&money="+params.get("money").toString()+
                         "&sendtime="+params.get("sendtime").toString()+
                         "&notifyurl="+params.get("notifyurl").toString()+
                         "&backurl="+params.get("backurl").toString()+
                          "&risklevel="+params.get("risklevel").toString();
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+key);
        String sign = SignUtils.MD5.createSign(signTxt, key, SignUtils.CHARSET_UTF8);
        return sign;
    }

    /**
     * 时间戳转时间(10位时间戳)
     *
     * @return
     */ public static String timestampToDate() {
        long timeStampSec = System.currentTimeMillis()/1000;
        String timestamp = String.format("%010d", timeStampSec);
        return  timestamp;
    }

}

